package per.mnxc.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import per.mnxc.common.BaseContext;
import per.mnxc.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @BelongsProject: spring_stu
 * @BelongsPackage: per.mnxc.filter
 * @Author: mnxc
 * @CreateTime: 2022-11-02  23:57
 * @Description: 登录过滤器
 * @Version: 1.0
 */

//@Slf4j
//@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        //请求路径白名单
        String[] urls = new String[]{
                "/admin/login",
                "/admin/logout",
                "/admin/sendMessage",
                "/admin/register",
                "/user/sendMessage",
                "/user/login",
                "/user/logout",
                "/user/register",
                "/backend/**",
                "/front/**",
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };
        //1.判断访问路径是否在白名单
        boolean check = check(urls, requestURI);

        if(check){
            //2.允许访问
            filterChain.doFilter(request,response);
            return;
        }

        if (request.getSession().getAttribute("adminId") != null) {
            //3.管理员已登录，允许通过
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("adminId"));
            filterChain.doFilter(request, response);
            return;
        }
        if (request.getSession().getAttribute("userId") != null) {
            //3.用户已登录，允许通过
            BaseContext.setCurrentId((Long) request.getSession().getAttribute("adminId"));
            filterChain.doFilter(request, response);
            return;
        }
        //4.未登录且访问路径不是白名单
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    boolean check(String[] urls,String uri){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, uri);
            if(match){
                return true;
            }
        }
        return false;
    }
}
